package com.xb.loan.cashier.alipay.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class WebUtil {

    public static Map<String, String> getRequetParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
            }
            System.out.println(name + " _ " + valueStr);
            params.put(name, valueStr);
        }
        return params;
    }

    public static String saveUploadFile(HttpServletRequest request) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = new ArrayList();
        try {
            items = upload.parseRequest(request);
            Iterator<FileItem> it = items.iterator();
            while (it.hasNext()) {
                FileItem fItem = (FileItem) it.next();
                if (!fItem.isFormField()) { 
                    String fileName = fItem.getFieldName();
                    String realpath = ServletActionContext.getServletContext().getRealPath("/file");
                    System.out.println("realpath: " + realpath);
                    File savefile = new File(new File(realpath), fileName);
                    if (!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();
                    FileUtils.copyInputStreamToFile(fItem.getInputStream(), savefile);
                    return fileName;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
